package info.niwota.webime;

import android.content.Context;
import android.content.res.Resources;
import android.content.res.XmlResourceParser;
import android.inputmethodservice.Keyboard;
import android.view.inputmethod.EditorInfo;

public class WebKeyboard extends Keyboard {
	public static final int ACTION_HELP = -1000;
	
	public static final int ACTION_RESET = -1001;

	public static final int ACTION_CLEAR = -1002;
	
	public static final int ACTION_SITE = -9999;

	private Key mEnterKey;


	public static int mapAction(String action) {
		if (action == null) {
			return EditorInfo.IME_ACTION_UNSPECIFIED;
		}
		final String[] keys = { "NONE", "GO", "SEARCH", "SEND", "NEXT", "DONE", "CLEAR", "RESET" };
		final int[] vals = { EditorInfo.IME_ACTION_NONE,
				EditorInfo.IME_ACTION_GO, EditorInfo.IME_ACTION_SEARCH,
				EditorInfo.IME_ACTION_SEND, EditorInfo.IME_ACTION_NEXT,
				EditorInfo.IME_ACTION_DONE, ACTION_CLEAR, ACTION_RESET };
		action = action.toUpperCase();
		for (int i = 0; i < keys.length; i++) {
			if (action.equals(keys[i])) {
				return vals[i];
			}
		}
		return EditorInfo.IME_ACTION_UNSPECIFIED;
	}
	
	public WebKeyboard(Context context, int xmlLayoutResId) {
		super(context, xmlLayoutResId);
	}

	public WebKeyboard(Context context, int layoutTemplateResId,
			CharSequence characters, int columns, int horizontalPadding) {
		super(context, layoutTemplateResId, characters, columns,
				horizontalPadding);
	}

	@Override
	protected Key createKeyFromXml(Resources res, Row parent, int x, int y,
			XmlResourceParser parser) {
		Key key = new LatinKey(res, parent, x, y, parser);
		if (key.codes[0] == 10) {
			mEnterKey = key;
		}
		return key;
	}

	void setImeOptions(Resources res, int options) {
		if (mEnterKey == null) {
			return;
		}

		switch (options
				& (EditorInfo.IME_MASK_ACTION | EditorInfo.IME_FLAG_NO_ENTER_ACTION)) {
		case EditorInfo.IME_ACTION_GO:
			mEnterKey.iconPreview = null;
			mEnterKey.icon = null;
			mEnterKey.label = res.getText(R.string.label_go_key);
			break;
		case EditorInfo.IME_ACTION_NEXT:
			mEnterKey.iconPreview = null;
			mEnterKey.icon = null;
			mEnterKey.label = res.getText(R.string.label_next_key);
			break;
		case EditorInfo.IME_ACTION_SEARCH:
			mEnterKey.icon = res.getDrawable(R.drawable.sym_keyboard_search);
			mEnterKey.label = null;
			break;
		case EditorInfo.IME_ACTION_SEND:
			mEnterKey.iconPreview = null;
			mEnterKey.icon = null;
			mEnterKey.label = res.getText(R.string.label_send_key);
			break;
		default:
			mEnterKey.icon = res.getDrawable(R.drawable.sym_keyboard_return);
			mEnterKey.label = null;
			break;
		}
	}

	static class LatinKey extends Keyboard.Key {

		public LatinKey(Resources res, Keyboard.Row parent, int x, int y,
				XmlResourceParser parser) {
			super(res, parent, x, y, parser);
		}

		@Override
		public boolean isInside(int x, int y) {
			return super.isInside(x, codes[0] == KEYCODE_CANCEL ? y - 10 : y);
		}
	}

}
